package com.zebra.gateway.protocol;

import com.zebra.gateway.processor.GatewayProcessorUtil;
import com.zebra.remoting.util.RemotingUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;


public class GatewayEncoder extends MessageToByteEncoder<GatewayCommand> {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(GatewayEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, GatewayCommand message, ByteBuf out) throws Exception{
        try {
            out.writeShort(message.getFlag());    // flag
            out.writeShort(message.getLength());  //length

            out.writeShort(message.getCmd());  //cmd
            out.writeLong(message.getToken());  // token
            out.writeLong(message.getUserId());  // token
            out.writeShort(message.getState());    //state
            out.writeShort(message.getGameId());     //gameId
            out.writeInt(message.getId());
            out.writeShort(message.getReserve());     //serverId

            out.writeBytes(message.getMsgBuf());
            if (!message.isLogs() && logger.isDebugEnabled()){
                logger.debug("Response c:{} {} {}",
                        message.getCmd(),  RemotingUtil.channelToString(ctx.channel()), message.toString());
            }

        }catch (Exception e){
            logger.error("ResponseEncoder c:{}   {} {} ", message.getCmd(),   RemotingUtil.channelToString(ctx.channel()), message.toString());
            logger.error("ResponseEncoder", e);
            throw  e;
        }finally {
            GatewayProcessorUtil.release(message);
        }

    }


}
